package com.mall.common.wxMa.utils;

import com.alibaba.fastjson.JSONObject;
import com.mall.common.core.asserts.ApiAssert;
import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.common.redis.utils.RedisUtils;
import com.mall.common.security.framework.aware.ApplicationUtils;
import com.mall.project.ma.cons.WxCons;
import com.mall.project.ma.model.dto.ThirdSession;

import javax.servlet.http.HttpServletRequest;

/**
 * @author www.joolun.com
 * 小程序工具类
 */
public class WxMaUtil {

    /**
     * 通过request获取appId
     *
     * @return
     * @throws Exception
     */
    public static String getAppId() {
        HttpServletRequest request = ApplicationUtils.getRequest();
        String appId = request.getHeader(WxCons.HEADER_APP_ID);
        return appId;
    }

    /**
     * 通过request获取appId
     *
     * @return
     * @throws Exception
     */
    public static String getThirdSession() {
        HttpServletRequest request = ApplicationUtils.getRequest();
        String thirdSessionHeader = request.getHeader(WxCons.HEADER_THIRDSESSION);
        String key = WxCons.THIRD_SESSION_BEGIN + ":" + thirdSessionHeader;
        RedisUtils redisUtils = ApplicationUtils.getBean(RedisUtils.class);
        String thirdSessionStr = redisUtils.get(key);
        ApiAssert.notStrEmpty(ErrorCodeEnum.UNAUTHORIZED, thirdSessionStr);
        ThirdSession thirdSession = JSONObject.parseObject(thirdSessionStr, ThirdSession.class);
        return thirdSession.getWxUserId();
    }
}
